package com.behelpful.common.core.utils;

import cn.hutool.core.util.StrUtil;
import com.behelpful.common.core.exceptions.ParamException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 *
 * @author Alay
 * @date 2021-12-15 13:22
 */
public class IEncryptUtil {


    /**
     * Md5 加密工具
     *
     * @param source
     * @param readyCode
     * @return
     */
    private static String md5(String source, char[] readyCode) {
        byte[] inputByte = source.getBytes();
        String algorithm = "md5";
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            byte[] outputByte = digest.digest(inputByte);
            for (int i = 0; i < outputByte.length; i++) {
                byte b = outputByte[i];
                int highValue = (b >> 4) & 15;
                int lowValue = b & 15;
                char highCharacter = readyCode[highValue];
                char lowCharacter = readyCode[lowValue];
                sb.append(highCharacter).append(lowCharacter);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * MD5加密工具方法
     *
     * @param source 明文
     * @return 密文
     */
    public static String md5(String source) {
        if (StrUtil.isBlank(source)) {
            ExceptionUtil.doThrow(ParamException.class);
        }
        // 自定义密文串
        char[] readyCode = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        return md5(source, readyCode);
    }

}
